# -*- coding: utf-8 -*- # 
"""Search movies for "Monty Python" and output the results.

Note: You should edit APIKEY to yours or you may be banned by service!
"""
from douban import BookEntry
import types
import urllib2
import urllib
import   os  
os.putenv("http_proxy",   "http://10.7.8.180:8080")   
os.putenv("https_proxy",   "http://10.7.8.180:8080")   
import datetime
import douban.service
import sqlite3
from apihelper import info

class doubanClient(douban.service.DoubanService):
    accessList = []
    maxcount = 5
    minAwaySec = 59
    logDataFile = "cache/douban/accessLog.sqlite"
    def __init__(self,api_key = None,accessChk = "DB"):
        douban.service.DoubanService.__init__(self,api_key)
        if accessChk == "DB":
            self.accessChkFunc = getattr(self, "prepareAccessByData")
            self.createLogData()
        else:
            self.accessChkFunc = getattr(self, "prepareAccessByStatic")
    @staticmethod
    def prepareAccessByStatic():
        print "prepareAccess"
        nowTime = datetime.datetime.now()
        if len(doubanClient.accessList) < doubanClient.maxcount:
            doubanClient.accessList.append(nowTime)
            return True
        else:
            firstTime = doubanClient.accessList[0]
            print "%s||%s" %(str(nowTime),str(firstTime))
            sec = (nowTime -firstTime).seconds
            if sec > doubanClient.minAwaySec:
                doubanClient.accessList.pop(0)
                doubanClient.accessList.append(nowTime)
                return True
        return False
    def prepareAccessByData(self,access_info = ""):
        cur = self.logConn.cursor()
        cur.execute("select * from accesslog order by acctime")
        res = cur.fetchall()
        nowTime = datetime.datetime.now()
        print len(res)
        if len(res) < doubanClient.maxcount:
            #self.logConn.execute("insert into accesslog(acctime,info) values ('%s', '%s')" %(str(nowTime),access_info))
            self.logConn.execute("insert into accesslog(acctime,info) values (?, ?)" ,(nowTime,access_info))
            return True
        else:
            
            firstTime = res[0][1]
            #firstTime = datetime.datetime(res[0][1])
            print "%s||%s" %(str(nowTime),str(firstTime))
            sec = (nowTime -firstTime).seconds
            print sec
            if sec > doubanClient.minAwaySec:
                #self.logConn.execute("delete accesslog where pkAccesslog = %s"%(str(res[0][0],)))
                #self.logConn.execute("insert into accesslog(acctime,info) values ('%s', '%s')" %(str(nowTime),access_info))
                print res[0][0]
                self.logConn.execute("delete from accesslog where pkAccesslog = ?",(res[0][0],))
                self.logConn.execute("insert into accesslog(acctime,info) values (?, ?)" ,(nowTime,access_info))
                return True
        return False 
        
    def createLogData(self):
        self.logConn = conn = sqlite3.connect(self.logDataFile,
                                               detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
        conn.isolation_level = None
        conn.execute("""create table 
                    if not exists accesslog 
                    (pkAccesslog integer primary key autoincrement, acctime timestamp, info varchar(128))""")
        
    
    def SearchBook(self,keyword):
        if self.accessChkFunc() == True:
            return douban.service.DoubanService.SearchBook(self,keyword)
class DoubanBookEntry():
    notAttrList = ["tag","attribute","rating"]
    def __init__(self,bookdata):
        self.bookdata = bookdata
        self.attrList = [attrstr for attrstr in dir(bookdata) \
                  if (
                      not callable(getattr(bookdata, attrstr)) and
                      not attrstr.startswith('_') and
                      not attrstr in self.notAttrList
                      )]
    
    def __getattr__(self,attr):
        print ""
        list = ["bookdata","notAttrList","attrList","printSelf"]
        if attr in list:
            return getattr(self,attr)
        return getattr(self.bookdata,attr)
    def printSelf(self):
        print "id:[%s]"%(self.bookdata.id and self.bookdata.id.text or "",)
        authors =  self.bookdata.author
        i = 0
        for attr in authors:
            i = i+1
            print "author [%03d]:[%s]" %(i,attr.name.text)
        print "title:[%s]"%(self.bookdata.title and self.bookdata.title.text or "",)
        print "summary:[%s]"%(self.bookdata.summary and self.bookdata.summary.text or "",)
        for attr in self.bookdata.attribute:
            print "attribute[%s]:[%s]" %(attr.name,attr.text)
        for tag in self.bookdata.tag:
            print "tag[%s]:[%s]" %(tag.name,tag.count)
        for link in self.bookdata.link:
            print "link[%s]:[%s]" %(link.rel,link.href)
        rate = self.bookdata.rating
        if rate != None :
            print dir( rate)
            print "average:%s"%(rate.average)
            print "max:%s"%(rate.max)
            print "min:%s"%(rate.min)
            print "numRaters:%s"%(rate.numRaters)

#    def getAttrStr(self,attr_name):
#        if attr_name in douban.BookEntry.attribute(self):
#            return self.attribute.text
#        return ""
#    def getAuthor(self):
#        """douban.BookEntry.author[0].name.text"""
#        return self.author
#    def getImageLink(self):
#        return self.GetImageLink().href
#    def getAlternateLink(self):
#        return self.GetAlternateLink().href
#    def getSelfLink(self):
#        return self.GetSelfLink().href
#    def getSummary(self):
#        """简介"""
#        return self.summary.text
#    def getAttrAuthor(self):
#        return self.getAttrStr("author")
#    
class netClient():
    def getFile(self,url,savePath,savename = None):
        pass
    pass
#    def searchBook(self,keyword):
#        feed = self.SearchBook(isbn)
#        for movie in feed.entry:
#            print "%s: %s" % (movie.title.text, movie.GetAlternateLink().href)
# Please use your own api key instead. e.g. :
if __name__ == "__main__":
    
    APIKEY = "23eeeb4347bdd26bfc6b7ee9a3b755dd"
    #APIKEY = None
    
    isbn = "7543639130"
    client = doubanClient(APIKEY)
    
#    url = r"http://api.douban.com/book/subject/2023013"
#    entry = client.GetBook(url)
#    bookEntry = DoubanBookEntry(entry)
#    bookEntry.printSelf()

    feed = client.SearchBook(isbn)
    for book in feed.entry:
        print "%s: %s" % (book.title.text, book.GetAlternateLink().href)
        #print movie.author[0].name.text

        bookEntry = DoubanBookEntry(book)
        bookEntry.printSelf()
